package com.javafactroy.kunlong.jsengine;


import cn.hutool.core.io.FileUtil;

import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static javax.script.ScriptContext.ENGINE_SCOPE;

// javascript计算引擎
public class JavascriptEngine {
    private static ScriptEngineManager scriptManager = new ScriptEngineManager();

    public static ScriptEngine getScriptEngine() {
        return scriptManager.getEngineByName("nashorn");//得到脚本引擎
    }

    // 解析变量
    public static List<String> parseVars(String expr) {

        List<String> vars = new ArrayList<>();
        Pattern p = Pattern.compile("\'?\\w+\'?|\"?\\w+\"?");        //attern p = Pattern.compile("(\\w+)\\s*(?=[,=])");

        Matcher m = p.matcher(expr);   //System.err.println("expr=" + expr);
        while (m.find()) {
            vars.add(m.group());     //System.err.println("find=" + m.group());
        }

        return vars;
    }

    public boolean isVar(String varName) {

        return false;
    }

    public static List<String> findExprParamNames(String expr) throws ScriptException {

        return parseVars(expr);

    }

    // 返回表达式变量
    public static Object doExpr(String expr, Map<String, Object> params) throws ScriptException {
        ScriptEngine engine = getScriptEngine();
        ScriptContext ctxt = engine.getContext();
        List<String> list = parseVars(expr);

        System.out.println("*** 全局参数 params = " + params);
        for (String i : list) {
            ctxt.setAttribute(i, params.get(i), ENGINE_SCOPE);
        }
        return engine.eval(expr);

    }

    // 执行函数
    public static Object doFunc(String expr, Map<String, Object> params) throws ScriptException {
        ScriptEngine engine = getScriptEngine();
        ScriptContext ctxt = engine.getContext();
        List<String> list = parseVars(expr);

        System.out.println(list);
        for (String i : list) {
            ctxt.setAttribute(i, params.get(i), ENGINE_SCOPE);
        }
        return engine.eval(expr);

    }

    public static void loadJsFile(ScriptEngine engine, String jsFile) throws IOException, ScriptException {

        //  String path = Thread.currentThread().getContextClassLoader().getResource("").getPath(); // 获取targe路径
        // engine.eval(new FileReader(path + "javascript/" +jsFile));
        String file = "./javascript/" + jsFile;
        String js= FileUtil.readUtf8String(file);
        engine.eval(js);
    }

    //loadJs
}
